/*
 * Copyright Â© 2012 by PropSage Pte Ltd. 
 * All Rights Reserved.
 * licensing@propsage.com
 * http://www.propsage.com/terms.html
 * 
 * @author Poh Nean
 */
propsage.namespace("propsage.brochure.widgets");

(function($){
	propsage.brochure.widgets.Image = {
		type: 'Image',
		template: '<div class="widget-placeholder image-placeholder" />',
		selectable: true,
		resizable: true,
		resizableOptions: {
			aspectRatio: true
		},
		draggable: true,
		rotatable: true,
		setup: function() {
			this.createChooseImageDialog();
		},
		init: function(data) {	
			var o = data.options;
			if (o.src == null) {
				o.src = '/images/no-image.png';
			}
		
			this._super(data);
		
			this.fitImage();
		},	
		getContents: function() {
			var o = this.options;
		
			var $img = $('<img style="height: 100%" />');		
			if (o.src != null) {
				$img.attr('src', o.src);
			}
		
			return $img;
		},
		onResize: function(e) {
			this.fitImage();
			
			this._super(e);
		},
		setImage: function(options) {
			var o = this.options;
			var aspectRatio = options.width / options.height;
			var newHeight = o.width / aspectRatio;
			var newWidth = newHeight * aspectRatio;
			
			o.src = options.src;
			o.width = newWidth;
			o.height = newHeight;
			
			this.widget.find('img').attr('src', o.src);			
			this.container.width(newWidth);
			this.container.height(newHeight);
			
			this.fitImage();
		},
		fitImage: function() {
		
		},
		openChooseImageDialog: function() {
			propsage.brochure.widgets.Image.chooseImageDialog.dialog("open");
		},
		createChooseImageDialog: function() {
			var widget = this;
			
			// create dialog			
			var timerID = null, selectedPhoto, selectedImageSource = null;
			var $dialog = $('<div id="dialog-chooseimage"/ >');
			var $sidebar = $('<div class="dialog-chooseimage-sidebar" />');
			var $tabs = $('<ul class="dialog-chooseimage-sources" />');
			
			// create sidebar tabs
			$.each(propsage.brochure.widgets.ImageSources, function(i, imageSource) {
				var $tab = $('<li class="dialog-chooseimage-source" />')
				.data('imagesource', imageSource);
				
				var $tabLink = $('<a href="#ChooseImage' + imageSource.name + '" />')
				.attr('id', 'dialog-chooseimage-source-' + imageSource.name)
				.text(imageSource.title)
				.appendTo($tab)
				;
				
				$tab.appendTo($tabs);
			});
			$tabs.appendTo($sidebar);
			$sidebar.appendTo($dialog);
			
			// create image grid view
			var $gridview = $('<div class="dialog-chooseimage-gridview" />');
			var $searchbar = $('<div class="dialog-chooseimage-search"><input type="text" /></div>');			
			var $albums = $('<div class="dialog-chooseimage-albums" />');
			
			$gridview
			.append($searchbar)
			.append($albums)
			.appendTo($dialog);
			
			$searchbar.hide(); // initlally hidden
			
			/** EVENT HANDLERS **/
			var onDialogOpen = function() {
				selectedPhoto = null;
				var maxHeight = ($(window).height() - 200);
				if (maxHeight < 400) {
					maxHeight = 400;
				}
		
				$dialog.css({
					'max-height': maxHeight + 'px'
				});
				$dialog.dialog( "option", "position", $dialog.dialog( "option", "position" ));
				
				$('#btnSelectPhoto').button('disable');
				
				if (selectedImageSource == null) {
					selectImageSource(propsage.brochure.widgets.ImageSources[0]);
				}
			};
			
			var onDialogCancel = function() {
				$dialog.dialog("close");
			}
			
			var onAlbumPhotoClick = function() {
				$('.dialog-chooseimage-albumphoto').removeClass('selected');
				
				var $this = $(this);
				var photoData = $this.data("albumPhoto");
				
				$this.addClass('selected');
				
				selectedPhoto = photoData;
				$('#btnSelectPhoto').button('enable');
			}
			
			var onBtnSelectClick = function() {
				if (selectedPhoto != null) {					
					widget.setImage({
						width: selectedPhoto.width,
						height: selectedPhoto.height,
						src: selectedPhoto.url
					});
					
					$dialog.dialog("close");
				}
			}
			
			var onLoadImageSourceSuccess = function(response) {
				$dialog.find('.dialog-chooseimage-source').removeClass('loading');
				
				selectedPhoto = null;
				$albums.empty();
				$searchbar.show();
				
				var albums = response.data.albums;
								
				if (albums.length > 0) {
					$.each(albums, function(i, album) {
						var $album = $('<div class="dialog-chooseimage-album"></div>');						
						var $albumName = $('<div class="dialog-chooseimage-albumname">' + album.name + ' <span class="dialog-chooseimage-albumcount">(' + album.photos.length + ')</span></div>');
						var $albumPhotos = $('<div class="dialog-chooseimage-albumphotos clearfix" />');
						
						$.each(album.photos, function(j, albumPhoto) {
							var $albumPhoto = $('<div class="dialog-chooseimage-albumphoto" />');
							
							var $albumPhotoImg = $('<img />')
							.attr('src', albumPhoto.thumbnail)
							.appendTo($albumPhoto);
							
							$albumPhoto
							.data("albumPhoto", albumPhoto)
							.appendTo($albumPhotos);
						});
						
						$album
						.data("album", album)
						.append($albumName)
						.append($albumPhotos)
						.appendTo($albums);
					});
				} else {
					
				}
				
				$dialog.dialog( "option", "position", $dialog.dialog( "option", "position" ));
			}
			
			var onLoadImageSourceFailure = function(response) {				
				$dialog.find('.dialog-chooseimage-source').removeClass('loading');
			}
			
			var onImageSourceClick = function(e) {
				var $this = $(this), imageSource = $(this).data("imagesource");
				
				selectImageSource(imageSource);
			};
			
			var selectImageSource = function(imageSource) {
				var $this = $(this), selectedImageSource = imageSource;
				
				$dialog.find('.dialog-chooseimage-source').removeClass('active');				
				$('#dialog-chooseimage-source-' + imageSource.name).closest('.dialog-chooseimage-source').addClass('active loading');
				
				propsage.ui.doAjax('GET', baseUrl + imageSource.source, {}, onLoadImageSourceSuccess, onLoadImageSourceFailure);
			}
			
			var onImageSearchKeydown = function(e) {
				var $this = $(this), searchTerm = '';
				clearTimeout(timerID);
				timerID = setTimeout(function() {
					searchTerm = $this.val().toLowerCase();
					
					$albums.find('.dialog-chooseimage-album').each(function() {
						var $album = $(this);
						var albumData = $album.data('album');
						
						if (albumData.name.toLowerCase().indexOf(searchTerm) == -1) {
							$album.hide();
						} else {
							$album.show();
						}
						
					});
				}, 100);
			}
			
			// dialog events
			$dialog.delegate('.dialog-chooseimage-source', 'click', onImageSourceClick);
			$dialog.delegate('.dialog-chooseimage-search input[type=text]', 'keydown', onImageSearchKeydown);
			$dialog.delegate('.dialog-chooseimage-albumphoto', 'click', onAlbumPhotoClick);
			
			// initialize dialog
			$dialog.appendTo('body');
			$dialog.dialog({
				'title': '<img src="/images/icons/farmfresh/16x16/pictures.png" />Choose Image',
				'dialogClass': 'dialog-choose-image',
				'autoOpen': false,
				'width': 800,
				'minHeight': 400,
				'maxHeight': 600,
				'resizable': false,
				'modal': true,
				'open': onDialogOpen,
				'buttons': {
					'Cancel': onDialogCancel,
					'Select': {
						'id': 'btnSelectPhoto',
						'text': 'Select',
						'class': 'blue',
						'click': onBtnSelectClick
					}
				}
			});
			
			propsage.brochure.widgets.Image.chooseImageDialog = $dialog;
		},
		handleActions: {
			close: {
				title: 'Delete Image',
				click: function(e) {
					var confirm = window.confirm('Delete Image?');

					if (confirm) {
						this.destroy();
					}
				}
			},
			edit: {
				title: 'Choose Image...',
				click: function(e) {
					this.openChooseImageDialog();
				}
			}
		},
		events: {
			mouseenter: function(e) {
				var self = this;
			}
		}
	};
	propsage.brochure.widgets.Image = propsage.brochure.Widget.extend(propsage.brochure.widgets.Image);
	
	
	propsage.brochure.widgets.ImageSources = [
		{
			name: 'propertycases',
			title: 'Transactions',
			source: '/ajax/template/listPropertyPhotos'
		},
		{
			name: 'floorplan',
			title: 'Floorplans',
			source: '/ajax/template/listFloorplanPhotos'
		},
//		{
//			name: 'mlslistings',
//			title: 'MLS Listings'
//		},
//		{
//			name: 'mydocuments',
//			title: 'My Documents'
//		}
	];
})(jQuery);